<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Article;
use app\admin\model\Articletype;
use app\admin\model\City;
use app\admin\model\Cmdlog;
use app\admin\model\Comment;
use app\admin\model\Devicelock;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdevice;
use app\admin\model\Shopjoin;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptableorder;
use app\admin\model\Shoptuan;
use app\admin\model\Tuanorder;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\admin\model\Userweixinmp;
use app\api\service\AirService;
use app\api\service\DeviceService;
use app\api\service\LockService;
use app\api\service\MpService;
use app\api\service\RoomService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use DateTime;
use Exception;
use fast\Http;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Cmd extends Api
{
    protected $noNeedLogin = ['wechatNotify', 'callback', 'orderCallback', 'statusCallback', 'sxfCallback', 'checkShare', 'tqCallback', 'backCheckTq'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    public function open2()
    {

        $msg = "";
        $type = $this->request->param('type');
        $order_no = $this->request->param('order_no');
        $user_id = $this->auth->getUser()['id'];


        $starTime = strtotime("+10 minute", time());

        $roomBookModel = new Shoproombook();
        $orderModel = new Shoporder();

        if ($type == 'door') {//大门

            if ($order_no != "") {
                $order = $orderModel->where('order_no', $order_no)->find();
                $book = $roomBookModel->where('order_id', $order['id'])->where('status', '<>', 'done')->find();
                if (!$book) {
                    $this->error("您没有预约的订单");
                }
            } else {
                $book = $roomBookModel->where('user_id', $user_id)->where('status', 'in', ['undo', 'doing'])->order('id', 'desc')->find();
            }


        } else {
            if ($order_no != "") {
                $orderModel = new Shoporder();
                $order = $orderModel->where('order_no', $order_no)->find();
                $book = $roomBookModel->where('order_id', $order['id'])->where('status', '<>', 'done')->find();
                if (!$book) {
                    $this->error("您没有预约的订单");
                }
            } else {
                $book = $roomBookModel->where('status', '<>', 'done')->where('user_id', $user_id)->order('id', 'desc')->find();

            }
        }

        if ($book['end_time'] < time()) {
            $roomBookModel->where('id', $book['id'])->update(['status' => 'done']);
            $this->error("暂无预约订单");
        }

        //error_log("==open2=book==".json_encode($book));
        $startTime = time();
        if ($startTime < $book['start_time'] && $type != 'door') {
            $endTime = $book['end_time'];
            $checkStart = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', "<=", $startTime)->where("end_time", ">=", $startTime)->find();
            $checkEnd = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();
            $checkEnd3 = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', ">=", $startTime)->where("end_time", "<=", $endTime)->find();

            if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
                $this->error("此时间不能提前开门");
            } else {
                $newMin = floor(($book['end_time'] - $book['start_time']) % 86400 / 60);

                $end = strtotime("+" . $newMin . " minute", time());
                //error_log("======test==".$end);
                $orderModel->where('id', $book['order_id'])->update(['book_start' => time(), 'book_end' => $end]);
                $roomBookModel->where('id', $book['id'])->update(['start_time' => time(), 'end_time' => $end]);
                $shopCleanModel = new Roomclean();

                $cleanEnd = strtotime("+30 minute", $end);
                $shopCleanModel->where('order_id', $book['order_id'])->update(['start_time' => $end, 'end_time' => $cleanEnd]);
                $book = $roomBookModel->where('id', $book['id'])->find();

            }


        } else {

            if ($starTime < $book['start_time']) {
                $this->error("您预约的时间未到");
            }
        }


        $msg = "正在开门中";

        $deviceModel = new Shopdevice();
        $sec = 0;
        if ($type == 'door') {//大门
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', -1)->find();
            $sec = 60;
            if ($device) {
                //发送指令
                $sn = $device['sn'];
                $req = array();
                $req['sec'] = $sec;
                $req['orderNo'] = getOrderSn();
                $req['sn'] = $sn;
                $req['voice'] = "欢迎光临";

                $ret = http_post_json($this->openCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
                if ($ret['code'] == 0) {
                    $msg = "正在打开中";
                }

                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => -1]);


            } else {
                $this->error("此包厢暂未绑定设备");
            }
        } else {//包厢
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('device_type', 'qp')->where('room_id', $book['room_id'])->find();
            $orderModel = new Shoporder();
            $order = $orderModel->where('id', $book['order_id'])->find();
            $orderNo = $order['order_no'];
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
            $sn = $device['sn'];

            $sec = $minute * 60;

            if ($device) {

//                if($device['status'] != 'online'){
//                    $this->error("设备没在线，请联系客服");
//                }
                if ($device['version'] == 1) {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderNo'] = $orderNo;
                    $req['sn'] = $sn;
                    $req['voice'] = "";

                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {

                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderId'] = $order['id'];
                    $req['deviceSn'] = $device['device_sn'];
                    $ret = http_post_json($this->openV3CmdUrl, json_encode($req));

                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                }


                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $book['room_id'])->update(['status' => 'busy']);

                $roomBookModel->where('id', $book['id'])->update(['status' => 'doing']);
                $orderModel->where('id', $book['order_id'])->update(['status' => 'doing']);
                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'order_no' => $orderNo, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => $book['room_id']]);

                //error_log("====cmd ret===".json_encode($ret));
            } else {
                $this->error("此包厢暂未绑定设备");

            }

        }

        $ret = array();
        $ret['is_bt'] = $device['is_bt'];
        $ret['room_id'] = $device['room_id'];
        $ret['shop_id'] = $device['shop_id'];



        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();
        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$device['shop_id'])->find();

                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['book_start'] = time();
                $lockReq['book_end'] = time() + $sec;
                $lockReq['lockId'] = $lock['lockId'];

                $lockService->openKtvLock($lockReq, $shop);//设置为订单期间常开

//                $lockService = new LockService();
//                $lockReq = array();
//                $lockReq['lockId'] = $lock['lockId'];
//                $lockService->openLock($lockReq);

            }
        }

        $roomService = new RoomService();
        $roomService->updateRoomFree($this->longRedis, $device['shop_id']);

        $this->success($msg, $ret);


    }


    /**
     * 提前到店
     */
    public function beforeOpen()
    {

        $order_no = $this->request->param('order_no');
        $orderModel = new Shoporder();
        $order = $orderModel->where('order_no', $order_no)->find();
        if ($order['status'] != 'payed') {
            $this->error("此订单状态不允许提前开门");
        }
        $startTime = time();
        $minute = floor(($order['book_end'] - $order['book_start']) % 86400 / 60);

        $endTime = strtotime("+" . $minute . " minute", $startTime);

        $time1 = $startTime;
        $time2 = $endTime;

        $id = $order['room_id'];

        //需要判断 和需要提前的订单是否是同一个订单
        $orderId = $order['id'];

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time2)->where('order_id', '<>', $orderId)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->where('order_id', '<>', $orderId)->find();
        $checkEnd3 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->where("end_time", "<=", $time2)->where('order_id', '<>', $orderId)->find();
        $checkEnd4 = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->where('order_id', '<>', $orderId)->find();

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null || $checkEnd4 != null) {
            $this->error("此时间段已被预定");
        }

        $shopRoomBookModel->where('order_id', $order['id'])->update(['start_time' => $startTime, 'end_time' => $endTime]);
        $orderModel->where('id', $order['id'])->update(['book_start' => $startTime, 'book_end' => $endTime]);
        $shopCleanModel = new Roomclean();
        $cleanEnd = strtotime("+" . 30 . " minute", $endTime);
        $shopCleanModel->where('order_id', $order['id'])->update(['start_time' => $endTime, 'end_time' => $cleanEnd]);

        $deviceModel = new Shopdevice();

        $user_id = $this->auth->getUser()['id'];

        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('device_type', 'qp')->where('room_id', $order['room_id'])->find();
        $orderNo = $order['order_no'];
        $sn = $device['sn'];
        $sec = $minute * 60;

        if ($device) {
            if ($device['version'] == 1) {
                $req = array();
                $req['sec'] = $minute * 60;
                $req['orderNo'] = $orderNo;
                $req['sn'] = $sn;
                $req['voice'] = "";
                $ret = http_post_json($this->openCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
                if ($ret['code'] == 0) {
                    $msg = "正在打开中";
                }
            } else {

                $req = array();
                $req['sec'] = $minute * 60;
                $req['orderId'] = $order['id'];
                $req['deviceSn'] = $device['device_sn'];
                $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
                if ($ret['code'] == 0) {
                    $msg = "正在打开中";
                }
            }

            $shopRoomModel = new Shoproom();
            $shopRoomModel->where('id', $order['room_id'])->update(['status' => 'busy']);

            $shopRoomBookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
            $orderModel->where('id', $order['id'])->update(['status' => 'doing']);

            $roomCleanModel = new Shoproom();
            $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


            $cmdModel = new Cmdlog();
            $cmdModel->insert(['user_id' => $user_id, 'order_no' => $orderNo, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['room_id']]);

            $ret = array();
            $ret['is_bt'] = $device['is_bt'];
            $ret['room_id'] = $device['room_id'];
            $ret['shop_id'] = $device['shop_id'];

            $deviceLockModel = new Devicelock();
            $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();
            if ($lock) {
                if ($lock['is_gateway'] == 1) {
                    $shopModel = new Shop();
                    $shop = $shopModel->where('id', $device['shop_id'])->find();

                    //网关开锁
                    $lockService = new LockService();
                    $lockReq = array();
                    $lockReq['book_start'] = time();
                    $lockReq['book_end'] = time() + $sec;
                    $lockReq['lockId'] = $lock['lockId'];

                    $lockService->openKtvLock($lockReq, $shop);//设置为订单期间常开

//                    $lockService = new LockService();
//                    $lockReq = array();
//                    $lockReq['lockId'] = $lock['lockId'];
//                    $lockService->openLock($lockReq);

                }
            }

            $roomService = new RoomService();
            $roomService->updateRoomFree($this->longRedis, $device['shop_id']);

            $this->success("", $ret);
        }


    }

    public function open()
    {

        $msg = "";
        $type = $this->request->param('type');
        $code = $this->request->param('code');
        $order_no = $this->request->param('order_no');
        $user_id = $this->auth->getUser()['id'];
        $user = $this->auth->getUser();

        if ($code != '') {

            $orderModel = new Shoporder();
            $order = $orderModel->where('status', "<>", 'done')->where('open_code', $code)->find();
            if ($order['status'] != 'paying') {
                $user_id = $order['user_id'];
            }
        }
        $min = 10;
        $orgModel = new Org();

        if ($order_no != "") {
            $orderModel = new Shoporder();
            $order = $orderModel->where('order_no', $order_no)->find();
            $org = $orgModel->where('id', $order['org_id'])->find();
            if ($org) {
                if ($org['id'] == 26 && $type == 'door') {
                    $min = 60;
                } else {
                    $min = $org['open_time'];
                }
            }


        } else {
            $org = $orgModel->where('id', $user['org_id'])->find();
            if ($org) {
                if ($org['id'] == 26 && $type == 'door') {
                    $min = 60;
                } else {
                    $min = $org['open_time'];
                }
            }
        }


        $starTime = strtotime("+" . $min . " minute", time());


        $roomBookModel = new Shoproombook();

        if ($order_no != "") {
            $orderModel = new Shoporder();
            $order = $orderModel->where('order_no', $order_no)->find();
            $book = $roomBookModel->where('order_id', $order['id'])->where('start_time', "<=", $starTime)->where('end_time', ">", time())->find();
            if ($book['status'] == 'done') {
                $this->error("您的订单已经结束，不可开门");
            }

            if (!$book) {
                $msg = "您预约时间未到，无法开门";
                $this->success($msg);
            }
            if ($book['start_time'] > $starTime) {

                $msg = "您预约时间未到，无法开门";

                $this->success($msg);
            }
        } else {

            $book = $roomBookModel->where('status', 'in', ['undo', 'doing'])->
            where('user_id', $user_id)->where('end_time', ">", time())->order('start_time', 'desc')->find();
            if (!$book) {
                $msg = "您没有预定的订单";
                $this->success($msg);
            }
            if ($book['start_time'] > $starTime) {

                $msg = "您预约时间未到，无法开门";

                $this->success($msg);
            }


        }


        if ($user['id'] == 6153) {
            //error_log("===cmd book=open2=".json_encode($book));

        } else {
            //error_log("===cmd book=open=".json_encode($book));

        }


        $msg = "发送开门指令";

        $sec = 0;
        $deviceModel = new Shopdevice();
        if ($type == 'door') {//大门
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', -1)->find();
            $sec = 60;
            if ($device) {
                //发送指令

                $sn = $device['sn'];
                $req = array();
                $req['sec'] = 60;
                $req['orderNo'] = getOrderSn();
                $req['sn'] = $sn;
                $req['voice'] = "欢迎光临";

                $ret = http_post_json($this->openCmdUrl, json_encode($req));
                $ret = json_decode($ret, true);
                if ($ret['code'] == 0) {
                    $msg = "正在打开中";
                }

                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => -1]);


            }
        } else {//包厢

            //error_log($order_no."=======".json_encode($book));
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('device_type', 'qp')->where('room_id', $book['room_id'])->find();
            $orderModel = new Shoporder();
            $order = $orderModel->where('id', $book['order_id'])->find();
            $orderNo = $order['order_no'];
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
            $sn = $device['sn'];
            $sec = $minute * 60;

            if ($device) {
                if ($device['version'] == 1) {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderNo'] = $orderNo;
                    $req['sn'] = $sn;
                    $req['voice'] = "";
                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {
                    $req = array();
                    $req['sec'] = $minute * 60;
                    $req['orderId'] = $order['id'];
                    $req['deviceSn'] = $device['device_sn'];
                    $ret = http_post_json($this->openV3CmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                }

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $book['room_id'])->update(['status' => 'busy']);

                $roomBookModel->where('id', $book['id'])->update(['status' => 'doing']);
                $orderModel->where('id', $book['order_id'])->update(['status' => 'doing']);

                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'order_no' => $orderNo, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => $book['room_id']]);

            }

        }


        $ret = array();
        $ret['is_bt'] = $device['is_bt'];
        $ret['room_id'] = $device['room_id'];
        $ret['shop_id'] = $device['shop_id'];

        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();

        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$device['shop_id'])->find();

                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['book_start'] = time();
                $lockReq['book_end'] = time() + $sec;
                $lockReq['lockId'] = $lock['lockId'];

                $lockService->openKtvLock($lockReq, $shop);//设置为订单期间常开

//                $lockService = new LockService();
//                $lockReq = array();
//                $lockReq['lockId'] = $lock['lockId'];
//                $lockService->openLock($lockReq);

            }
        }

        $this->success($msg, $ret);


    }


    public function getXuList()
    {
        $user = $this->auth->getUser();
        $starTime = strtotime("-10 minute", time());
        $roomBookModel = new Shoproombook();
        $list = $roomBookModel->where('status', 'doing')->
        where('user_id', $user['id'])->where('end_time', ">", $starTime)->limit(3)->select();

        $shopOrderModel = new Shoporder();
        foreach ($list as $key => $val) {
            $order = $shopOrderModel->where('id', $val['order_id'])->find();
            $list[$key]['order'] = $order;
        }
        $this->success('', $list);
    }

    public function xu()
    {

        $user = $this->auth->getUser();
        $brand = $this->request->param('brand');

        $orderNo = $this->request->param('order_no');
        $starTime = strtotime("-10 minute", time());

        $roomBookModel = new Shoproombook();
        if ($orderNo != "") {
            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $orderNo)->find();
            $book = $roomBookModel->where('order_id', $order['id'])->find();
        } else {
            $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
            where('user_id', $user['id'])->order('end_time', 'desc')->find();

        }
        $count = $roomBookModel->where('status', 'doing')->
        where('user_id', $user['id'])->where('end_time', ">", $starTime)->count('id');

        if ($book['end_time'] < $starTime) {
            $this->error("您没有可续费的订单");
        }
        if ($book['end_time'] - time() < 0) {
            $minute = 0;
        } else {
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
        }
        $shopModel = new Shop();
        $shopRoomModel = new Shoproom();
        $shop = $shopModel->where('id', $book['shop_id'])->find();


        $room = $shopRoomModel->where('id', $book['room_id'])->find();

        $commentModel = new Comment();
        $comment = $commentModel->where('user_id', $book['user_id'])->where('shop_id', $book['shop_id'])->where('status', 'undo')->find();
        $isComment = -1;
        if ($comment) {
            $isComment = 1;
        }
        $ret = array();
        $ret['name'] = $shop['name'];
        $ret['room_name'] = $room['name'];
        $ret['hour_price'] = $room['hour_price'];
        $ret['price'] = $room['hour_price'] * 1;
        $ret['id'] = $book['id'];
        $ret['hour'] = 1;
        $ret['isComment'] = $isComment;
        $ret['min'] = $minute;
        $ret['logo'] = cdnurl($shop['logo'], true);

        $ret['count'] = $count;

        $this->success('', $ret);

    }


    /**
     * 续费支付
     */
    public function xufeiPay()
    {


        $hour = $this->request->param('hour');
        $id = $this->request->param('id');
        $user = $this->auth->getUser();

        $roomBookModel = new Shoproombook();
        if ($id) {
            $book = $roomBookModel->where('id', $id)->where('status', 'in', ['doing', 'done'])->find();
        } else {
            $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
            where('user_id', $user['id'])->order('id', 'desc')->find();
        }
        if (!$book) $this->error("此订单不符合续费订单");

        $id = $book['room_id'];
        $order_id = $book['order_id'];

        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $book['room_id'])->find();
        $xuMin = $hour * 60;

        $startTime = time();
        if ($book['end_time'] - $startTime > 0) {
            $haveMin = floor(($book['end_time'] - $startTime) % 86400 / 60);
        } else {
            $haveMin = 0;
        }

        $totalMin = $haveMin + $xuMin;
        $endTime = strtotime("+" . $totalMin . " minute", time());

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $book['shop_id'])->find();

        if ($shop['open_time'] != "") {
            $openTime = $shop['open_time'];
            $openTimes = explode("~", $openTime);
            $openStart = $openTimes[0];
            $openEnd = $openTimes[1];


            $ymd = date("Y-m-d", $endTime);
            $openStart = strtotime($ymd . " " . $openStart . ":00");
            $openEnd = strtotime($ymd . " " . $openEnd . ":00");

            if ($endTime >= $openStart && $endTime <= $openEnd) {
                $this->error("该店铺即将歇业,不可续费");
            }

        }


        $time1 = $startTime;
        $time2 = $endTime;
        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('id', '<>', $id)->where('room_id', $book['room_id'])->where('status', 'in', ['undo', 'doing'])->order('start_time', 'desc')->where('start_time', ">=", time())->select();
        foreach ($bookList as $key => $val) {

            $start = $val['start_time'];
            $end = $val['end_time'];
            if ($time1 <= $start && $time2 >= $end) $isBooked = 1;//全包围
            if ($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
            if ($time1 <= $end && $time2 > $end) $isBooked = 1; //
            if ($time1 < $start && $time2 <= $end && $time2 >= $start) $isBooked = 1;

        }
        if ($isBooked == 1) $this->error("此时间段已被预定");

        $totalPrice = $hour * $room['hour_price'];

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;
        if ($balance > 0) {
            $type = "balance";
            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $totalPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $startTime;
        $db['book_end'] = $endTime;
        $db['set_id'] = -1;
        $db['balance'] = $dis_price;
        $db['org_id'] = $shop['org_id'];


        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);

        if ($id > 0) {
            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定".$hour."小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//
//                $info['order_no'] = $orderNo;
//                $info['payInfo'] = json_decode($result, true);

                $orgModel = new Org();
                $org = $orgModel->where('id', $shop['org_id'])->find();

                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

//                        $realPay = $pay_price- $pay_price*0.006;
//                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);
                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }


                $req['mno'] = $mno;//纷享未来药房
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/sxfCallback";
                $req['subject'] = "包厢续费";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }

            } else {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($type == "balance") {

                    $userBalanceModel = new Userbalance();
                    $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                        'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
                }

                $orderModel = new Shoporder();
                $orderModel->where('order_no', $orderNo)->update(['status' => 'doing']);

                $order = $shopOrderModel->where('id', $id)->find();
                $bookModel = new Shoproombook();

                $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
                if ($lastOrder) {
                    $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                    $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                }


                $roomService = new RoomService();
                $roomService->addBookData($order);


                $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $this->redis->set($order['shop_id'], time());

                $deviceService = new DeviceService();
                $book = $bookModel->where('order_id', $order['id'])->find();

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);

                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
                if ($device['version'] == 1) {
                    $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
                } else {
                    $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);

                }
            }


            $this->success('下单成功', $info);
        } else {
            $this->error('续费失败，请联系客服');

        }


    }

    public function xufeiPayV2()
    {


        $hour = $this->request->param('hour');
        $id = $this->request->param('id');
        $user = $this->auth->getUser();

        $roomBookModel = new Shoproombook();
        if ($id) {
            $book = $roomBookModel->where('id', $id)->where('status', 'in', ['doing', 'done'])->find();
        } else {
            $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
            where('user_id', $user['id'])->order('id', 'desc')->find();
        }
        if (!$book) $this->error("此订单不符合续费订单");

        $id = $book['room_id'];
        $order_id = $book['order_id'];

        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $book['room_id'])->find();
        $xuMin = $hour * 60;

        $startTime = time();
        if ($book['end_time'] - $startTime > 0) {
            $haveMin = floor(($book['end_time'] - $startTime) % 86400 / 60);
        } else {
            $haveMin = 0;
        }

        $totalMin = $haveMin + $xuMin;
        $endTime = strtotime("+" . $totalMin . " minute", time());

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $book['shop_id'])->find();

//        if ($shop['open_time'] != "") {
//            $openTime = $shop['open_time'];
//            $openTimes = explode("~", $openTime);
//            $openStart = $openTimes[0];
//            $openEnd = $openTimes[1];
//
//
//            $ymd = date("Y-m-d", $endTime);
//            $openStart = strtotime($ymd . " " . $openStart . ":00");
//            $openEnd = strtotime($ymd . " " . $openEnd . ":00");
//
//            if ($endTime >= $openStart && $endTime <= $openEnd) {
//                $this->error("该店铺即将歇业,不可续费");
//            }
//
//        }

        if($shop['open_time'] != ""){
            if (!$this->checkUseTime($startTime, $endTime, $shop['open_time'])) {
                $this->error('营业时间:【' . $shop['open_time'] . '】');
            }
        }

        //新-续费时，判断包间是否被占用
//        $bookTimes = $roomBookModel->where('room_id', $id)->where('status', 'in', ['doing', 'undo'])->where('order_id', '<>', $book['order_id'])->select();
//        if (!empty($bookTimes)) {
//            foreach ($bookTimes as $bookTime) {
//                if ($this->isOverlap($startTime, $endTime, $bookTime['start_time'], $bookTime['end_time'])) {
//                    $this->error("此时间段已被预定,不能续费");
//                }
//            }
//        }


        $time1 = $startTime;
        $time2 = $endTime;
        $isBooked = -1;
        $shopRoomBookModel = new Shoproombook();
        $bookList = $shopRoomBookModel->where('room_id',$id)->where('status','in',['undo','doing'])->where('order_id', '<>', $book['order_id'])->order('start_time','desc')->select();
        foreach ($bookList as $key=>$val){

            $start = $val['start_time'];
            $end = $val['end_time'];
            if($time1 <=$start &&  $time2 >= $end) $isBooked = 1;//全包围
            if($time1 >= $start && $time2 <= $end) $isBooked = 1;//在区间范围内
            if($time1 <= $end && $time2 >$end) $isBooked = 1; //
            if($time1 < $start && $time2 <=$end && $time2 >= $start) $isBooked = 1;

        }
        if($isBooked == 1) $this->error("此时间段已被预定");

        $totalPrice = $hour * $room['hour_price'];

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;
        if ($balance > 0) {
            $type = "balance";
            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $totalPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $startTime;
        $db['book_end'] = $endTime;
        $db['set_id'] = -1;
        $db['balance'] = $dis_price;
        $db['org_id'] = $shop['org_id'];


        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);

        if ($id > 0) {
            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定".$hour."小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//
//                $info['order_no'] = $orderNo;
//                $info['payInfo'] = json_decode($result, true);

                $orgModel = new Org();
                $org = $orgModel->where('id', $shop['org_id'])->find();

                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

//                        $realPay = $pay_price- $pay_price*0.006;
//                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);
                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }


                $req['mno'] = $mno;//纷享未来药房
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/sxfCallback";
                $req['subject'] = "包厢续费";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }

            } else {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                $orderModel = new Shoporder();
                $orderModel->where('order_no', $orderNo)->update(['status' => 'doing']);

                $order = $shopOrderModel->where('id', $id)->find();
                $bookModel = new Shoproombook();

                $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
                if ($lastOrder) {
                    $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                    $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                }

                if ($type == "balance") {

                    $userBalanceModel = new Userbalance();
                    $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                        'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
                }

                $roomService = new RoomService();
                $roomService->addBookData($order);

                $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $this->redis->set($order['shop_id'], time());

                $deviceService = new DeviceService();
                $book = $bookModel->where('order_id', $order['id'])->find();

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);

                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
                if ($device['version'] == 1) {
                    $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
                } else {
                    $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);
                }



                $room = $shopRoomModel->where('id',$book['room_id'])->find();
                $key = str_replace(':', '', $room['mac']);
                $shopOrderModel = new Shoporder();
                $order = $shopOrderModel->where('room_id', $room['id'])->where('status', 'doing')->order('book_start', 'desc')->find();

                $shopModel = new Shop();
                $shop = $shopModel->where('id', $room['shop_id'])->find();
                $time = "";
                if ($order) {
                    $time = date("Y-m-d H:i:s", $order['book_end']);
                }
                $url = cdnurl($shop['qr_code'], true);
                $obj = array();
                $obj['time'] = $time;
                $obj['url'] = $url;
                $this->redis->set($key, json_encode($obj));

            }

            $this->success('下单成功', $info);
        } else {
            $this->error('续费失败，请联系客服');

        }


    }


    /**
     * 续费支付
     */
    public function xufeiPayFz()
    {


        $hour = $this->request->param('hour');

        $user = $this->auth->getUser();


        $roomBookModel = new Shoproombook();
        $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
        where('user_id', $user['id'])->order('end_time', 'desc')->find();

        $id = $book['room_id'];


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $book['room_id'])->find();

        $xuMin = $hour * 60;


        $startTime = time();
        if ($book['end_time'] - $startTime > 0) {
            $haveMin = floor(($book['end_time'] - $startTime) % 86400 / 60);
        } else {
            $haveMin = 0;
        }


        $totalMin = $haveMin + $xuMin;

        $endTime = strtotime("+" . $totalMin . " minute", time());

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $book['shop_id'])->find();

        $checkStart = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $startTime)->where("end_time", ">=", $endTime)->find();
        $checkEnd = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();

        if ($checkStart != null || $checkEnd != null) {

            if ($checkStart['id'] != $id || $checkEnd['id'] == $id) {
                $this->error("此时间段预被预定,无法续费");
            }
        }


        $totalPrice = $hour * $room['hour_price'];

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;
        if ($balance > 0) {
            $type = "balance";
            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $totalPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $startTime;
        $db['book_end'] = $endTime;
        $db['set_id'] = -1;
        $db['balance'] = $dis_price;
        $db['org_id'] = $shop['org_id'];


        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);

        if ($id > 0) {
            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定".$hour."小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//
//                $info['order_no'] = $orderNo;
//                $info['payInfo'] = json_decode($result, true);

                $orgModel = new Org();
                $org = $orgModel->where('id', $shop['org_id'])->find();


                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

//                        $realPay = $pay_price- $pay_price*0.006;
//                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);
                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio'] * $realPay / 100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;

                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/sxfCallback";
                $req['subject'] = "包厢续费";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }

            } else {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                $orderModel = new Shoporder();
                $orderModel->where('order_no', $orderNo)->update(['status' => 'doing']);

                $order = $shopOrderModel->where('id', $id)->find();
                $bookModel = new Shoproombook();

                $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
                if ($lastOrder) {
                    $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                    $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                }

                $roomService = new RoomService();
                $roomService->addBookData($order);
                $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $this->redis->set($order['shop_id'], time());

                $deviceService = new DeviceService();
                $book = $bookModel->where('order_id', $order['id'])->find();

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
                if ($device['version'] == 1) {
                    $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
                } else {
                    $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);

                }

            }
            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error('续费失败，请联系客服');

        }


    }


    /**
     * 续费支付 多笔分账
     */
    public function xufeiPayFzMore()
    {


        $hour = $this->request->param('hour');

        $user = $this->auth->getUser();


        $roomBookModel = new Shoproombook();
        $book = $roomBookModel->where('status', 'in', ['doing', 'done'])->
        where('user_id', $user['id'])->order('end_time', 'desc')->find();

        $id = $book['room_id'];


        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $book['room_id'])->find();

        $xuMin = $hour * 60;


        $startTime = time();
        if ($book['end_time'] - $startTime > 0) {
            $haveMin = floor(($book['end_time'] - $startTime) % 86400 / 60);
        } else {
            $haveMin = 0;
        }


        $totalMin = $haveMin + $xuMin;

        $endTime = strtotime("+" . $totalMin . " minute", time());

        $shopModel = new Shop();
        $shop = $shopModel->where('id', $book['shop_id'])->find();

        $checkStart = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $startTime)->where("end_time", ">=", $endTime)->find();
        $checkEnd = $roomBookModel->where('room_id', $id)->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();

        if ($checkStart != null || $checkEnd != null) {

            if ($checkStart['id'] != $id || $checkEnd['id'] == $id) {
                $this->error("此时间段预被预定,无法续费");
            }
        }


        $totalPrice = $hour * $room['hour_price'];

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;
        if ($balance > 0) {
            $type = "balance";
            if ($balance >= $totalPrice) {
                $dis_price = $totalPrice;
                $pay_price = 0;
            } else {
                $dis_price = $balance;
                $pay_price = $totalPrice - $balance;
            }

        }
        $orderNo = getOrderSn();
        $db = array();
        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $totalPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $startTime;
        $db['book_end'] = $endTime;
        $db['set_id'] = -1;
        $db['balance'] = $dis_price;
        $db['org_id'] = $shop['org_id'];


        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);

        if ($id > 0) {
            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定".$hour."小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/wechatNotify";
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);
//
//                $info['order_no'] = $orderNo;
//                $info['payInfo'] = json_decode($result, true);

                $orgModel = new Org();
                $org = $orgModel->where('id', $shop['org_id'])->find();


                $shopMnoModel = new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
                $mno = $org['mno'];
                if ($shopMno) {
                    if ($shopMno['ratio'] == 100) {
                        //走挂靠
                        $mno = $shopMno['mno'];
                    } else {

                        $listMnos = $shopMnoModel->where('shop_id', $shop['id'])->select();
                        $fs = array();
                        $realPay = formatMoney($pay_price - $pay_price * 0.006);
                        foreach ($listMnos as $key => $val) {
                            //走分账
                            $fusruleId = array();
                            $fusruleId['mno'] = $val['mno'];
                            $fusruleId['allotValue'] = formatMoney($val['ratio'] * $realPay / 100);
                            $fs[] = $fusruleId;

                        }

                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;

                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];
                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/cmd/sxfCallback";
                $req['subject'] = "包厢续费";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;


                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }

            } else {
                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                $orderModel = new Shoporder();
                $orderModel->where('order_no', $orderNo)->update(['status' => 'doing']);

                $order = $shopOrderModel->where('id', $id)->find();
                $bookModel = new Shoproombook();

                $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
                if ($lastOrder) {
                    $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                    $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                }

                $roomService = new RoomService();
                $roomService->addBookData($order);
                $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
                $this->redis->set($order['shop_id'], time());

                $deviceService = new DeviceService();
                $book = $bookModel->where('order_id', $order['id'])->find();

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                $deviceModel = new Shopdevice();
                $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
                if ($device['version'] == 1) {
                    $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
                } else {
                    $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);

                }

            }
            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }


            $this->success('下单成功', $info);
        } else {
            $this->error('续费失败，请联系客服');

        }


    }

    public function sxfCallback()
    {

        $param = file_get_contents("php://input");
        //error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);


            $shopOrderModel = new Shoporder();
            $bookModel = new Shoproombook();
            $shopCleanModel = new Roomclean();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();

            $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('order_no',"<>",$out_trade_no)->where('status', 'doing')->find();
            $xu_order_no = "";
            if ($lastOrder) {
                $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                $shopCleanModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);
                $xu_order_no = $lastOrder['order_no'];
            }

            if ($order['pay_amount'] > 0 && $order['balance'] > 0) {
                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'out',
                    'amount' => $order['balance'], 'mark' => $order['shop_name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $order['shop_id'], 'order_id' => $order['id']]);
            }


            $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing', 'update_time' => time(), 'xu_order_no' => $xu_order_no]);


            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();

            $pay_price = $order['pay_amount'];
            $realPay = formatMoney($pay_price - $pay_price * 0.006);
            $shopProfit = formatMoney((100 - $shop['ratio']) * $realPay / 100);
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => $shopProfit]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }


            $deviceService = new DeviceService();
            $this->redis->set($order['shop_id'], time());
            $roomService = new RoomService();
            $roomService->addBookData($order);

            $shopRoomModel = new Shoproom();
            $shopRoomModel->where('id', $order['room_id'])->update(['is_clean' => 1]);

            $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
            $book = $bookModel->where('order_id', $order['id'])->find();

            $deviceModel = new Shopdevice();
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
            if ($device['version'] == 1) {
                $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
            } else {
                $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);

            }


            $room = $shopRoomModel->where('id',$book['room_id'])->find();
            $key = str_replace(':', '', $room['mac']);

            $shopModel = new Shop();
            $shop = $shopModel->where('id', $room['shop_id'])->find();
            $time = "";
            if ($order) {
                $time = date("Y-m-d H:i:s", $order['book_end']);
            }
            $url = cdnurl($shop['qr_code'], true);
            $obj = array();
            $obj['time'] = $time;
            $obj['url'] = $url;
            $this->redis->set($key, json_encode($obj));


        }
    }

    public function wechatNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $shopOrderModel = new Shoporder();
            $bookModel = new Shoproombook();

            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();

            $lastOrder = $shopOrderModel->where('user_id', $order['user_id'])->where('status', 'doing')->find();
            if ($lastOrder) {
                $shopOrderModel->where('id', $lastOrder['id'])->update(['status' => 'done']);
                $bookModel->where('order_id', $lastOrder['id'])->update(['status' => 'done']);

            }
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'doing', 'update_time' => time()]);


            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }


            $deviceService = new DeviceService();
            $this->redis->set($order['shop_id'], time());
            $book = $bookModel->where('order_id', $order['id'])->find();
            $roomService = new RoomService();
            $roomService->addBookData($order);
            $bookModel->where('order_id', $order['id'])->update(['status' => 'doing']);
            $book = $bookModel->where('order_id', $order['id'])->find();


            $deviceModel = new Shopdevice();
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
            if ($device['version'] == 1) {
                $deviceService->openRoom($book, $order['user_id'], $this->openCmdUrl);
            } else {
                $deviceService->openRoom($book, $order['user_id'], $this->openV3CmdUrl);

            }


        }
        return $pay->success();
    }


    public function orderCallback()
    {

        $param = file_get_contents("php://input");
        //error_log(date("Y-m-d H:i:s")."=orderCallback=====" . $param);
        $result = json_decode($param, true);

        $response = array();
        $response['code'] = 1;
        $response['msg'] = "success";
        $response['data'] = "";


        echo json_encode($response);

        $order_no = $result['orderNo'];
        $deviceSn = $result['deviceSn'];
        $airService = new AirService();

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('sn', $deviceSn)->find();
        if ($device['device_type'] == 'qp') {
            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $order_no)->find();
            $shopRoomModel = new Shoproom();
            $org_id = $order['org_id'];


            if ($order) {
                $shopOrderModel->where('id', $order['id'])->update(['status' => 'done']);
                $shopBookModel = new Shoproombook();
                $room = $shopRoomModel->where('id', $order['room_id'])->find();

                if ($order['status'] != "done" && $room['status'] != 'stop') {
                    $shopRoomModel->where('id', $order['room_id'])->update(['status' => 'free', 'is_clean' => -1]);

                }
                $shopBookModel->where('order_id', $order['id'])->update(['status' => 'done']);


            }

            if ($order) {
                $shopStaffModel = new Shopstaff();
                $staffList = $shopStaffModel->where('shop_id', $order['shop_id'])->select();
                $mpWxModel = new Userweixinmp();
                $mpService = new MpService();
                foreach ($staffList as $key => $val) {
                    if ($org_id == 53) {
                        //小胡童
                        $wx = $mpWxModel->where('mobile', $val['mobile'])->where('org_id', 53)->find();
                    } else {
                        $wx = $mpWxModel->where('mobile', $val['mobile'])->find();
                    }

                    if ($wx) {
                        $obj = array();
                        $obj['openid'] = $wx['openid'];
                        $obj['shop'] = $order['shop_name'];
                        $obj['room'] = $order['room_name'];
                        $obj['time1'] = date("Y-m-d h:i", $order['book_start']);
                        $obj['time2'] = date("Y-m-d h:i", $order['book_end']);

                        if ($org_id == 53) {

                            $mpService->xhtCleanStartNotify($this->xhtWxApp, $obj);

                        } else {
                            $mpService->cleanStartNotify($this->wxApp, $obj);

                        }

                    }
                }

            }
        } else {

            $shopTableOrderModel = new Shoptableorder();
            $order = $shopTableOrderModel->where('order_no', $order_no)->find();
            if ($order) {

                if ($order['is_done'] == 1) return;

                $db = array();
                $db['status'] = "done";
                $db['book_end'] = time();
                $db['is_done'] = 1;
                //更改台桌状态
                $shopTableModel = new \app\admin\model\Shoptable();
                $shopTableModel->where('id', $order['table_id'])->update(['status' => 'free']);


                $airService = new AirService();
                $airService->airCheck($order['shop_id']);
                $airService->airCheckV2($order['shop_id'], $order['table_id']);


                //抖音核销
                //美团核销
                //团购券
                //在线支付
                if ($order['ya_amount'] > 0 || $order['balance'] > 0) {
                    $amount = $order['ya_amount'] + $order['balance'];
                    if ($order['ya_amount'] > 0) {
                        $payAmount = $order['ya_amount'];
                    } else {
                        $payAmount = 0;
                    }
                    $db['amount'] = $amount;
                    $db['pay_amount'] = $payAmount;


                    if ($order['ya_amount'] > 0) {
                        $userBalanceModel = new Userbalance();
                        $balance = $userBalanceModel->balance($order['shop_id'], $order['user_id']);
                        if ($balance > 0) {
                            $db['pay_amount'] = $order['pay_amount'] - $balance;
                            $db['refund_amount'] = $balance;
                            $db['update_time'] = time();

                        }
                    }
                }
                //在线支付+余额
                $shopTableOrderModel->where('id', $order['id'])->update($db);
                $shopModel = new Shop();
                $shop = $shopModel->where('id', $order['shop_id'])->find();
                //发放分润
                if ($db['pay_amount'] > 0) {
                    $pay_rate = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
                    $rate = formatMoney($shop['ratio'] * $db['pay_amount'] / 100);

                    $profit = $db['pay_amount'] - $pay_rate - $rate;
                    if ($profit > 0) {
                        $shopOrderProfitModel = new Shoporderprofit();
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($profit)]);
                    }
                }


                if ($db['refund_amount'] > 0) {
                    $req = array();
                    $req['mno'] = $this->mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = formatMoney($db['refund_amount']);
                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);

                }
            }
        }


        $roomService = new RoomService();
        $roomService->updateRoomFree($this->longRedis, $order['shop_id']);


    }

    public function statusCallback()
    {

        $param = file_get_contents("php://input");
        //error_log("=statusCallback=====" . $param);
        $result = json_decode($param, true);

        $deviceSn = $result['deviceSn'];
        $status = $result['status'];
        $deviceModel = new Shopdevice();
        $shopRoomModel = new Shoproom();
        $device = $deviceModel->where('device_sn', $deviceSn)->find();
        if ($device) {
            $deviceModel->where('id', $device['id'])->update(['status' => $status]);
            $room = $shopRoomModel->where('id', $device['room_id'])->find();
            if ($room['status'] != 'stop') {
                $shopRoomModel->where('id', $device['room_id'])->update(['status' => 'free']);
            }
        }

//        if($status == 'offline'){
//
//            $mpWxModel = new Userweixinmp();
//            $shop_id =  $device['shop_id'];
//            $shopModel = new \app\admin\model\Shop();
//            $shop = $shopModel->where('id',$shop_id)->find();
//            $wx = $mpWxModel->where('mobile',$shop['mobile'])->find();
//            if($wx){
//
//                $obj = array();
//                $obj['openid'] = $wx['openid'];
//                $obj['device'] = $deviceSn;
//                $obj['shop'] = $shop['name'];
//                $obj['time'] = date("Y-m-d H:i");
//
//                $mpService = new MpService();
//                $mpService->offlineNotify($this->wxApp,$obj);
//            }
//        }


        $this->success('成功');
    }

    public function checkShare()
    {

        $user = $this->auth->getUser();
        if ($user) {

            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('status', 'in', ['payed', 'doing'])->where('user_id', $user['id'])->order('id', 'desc')->find();

            $this->success('', $order);
        } else {
            $this->error("暂无预约订单");
        }
    }

    public function tqCallback()
    {

        $param = file_get_contents("php://input");
        $result = json_decode($param, true);

        error_log("==tqCallback======" . json_encode($result));
        $weigh = $result['weigh'];
        $lock = $result['lock'];
        $deviceSn = $result['deviceSn'];


        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('sn', $deviceSn)->find();
        if ($device['sn'] == 2847) {


            $weigh = $weigh - 787;
            $one = 165;
            $num = floor($weigh / $one);
            if ($num == 0 && $weigh > 100 && $weigh < 200) {
                $num = 1;
            }
            $is_qiu = -1;
            if ($num >= 16) {
                $is_qiu = 1;
            }
            //error_log("====设备号==".$deviceSn."=====重量=====".$weigh."====数量====".$num);

        } else {
            $one = 200;
            $weigh = $weigh;
            $num = floor($weigh / $one);
            if ($num == 0 && $weigh > 100 && $weigh < 200) {
                $num = 1;
            }
            $is_qiu = -1;
            if ($num >= 16) {
                $is_qiu = 1;
            }
        }

        $orderModel = new Shoptableorder();

        $orderModel->where('table_id', $device['room_id'])->where('status', 'doing')->update(['is_lock' => $lock, 'num' => $num, 'is_qiu' => $is_qiu]);

    }

    public function checkTq()
    {

        $order_no = $this->request->param('order_no');
        $tqOrderModel = new Shoptableorder();
        $order = $tqOrderModel->where('order_no', $order_no)->find();
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        if ($device) {
            $req = array();
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];


            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
            }
        }

        $status = -1;

        if ($order['is_qiu'] == 1) {
            $status = 1;//已完成
        }

        $num = $order['num'];

        $ret = array();
        $ret['num'] = $num;
        $ret['status'] = $status;
        $this->success('', $ret);

    }

    public function backCheckTq()
    {
        $tqOrderModel = new Shoptableorder();
        $list = $tqOrderModel->where('is_lock', 2)->where('status', 'done')->order('book_end', 'desc')->limit(20)->select();


    }


    public function dxOpen()
    {

        $msg = "";
        $type = $this->request->param('type');
        $code = $this->request->param('code');
        $order_no = $this->request->param('order_no');
        $user_id = $this->auth->getUser()['id'];
        $user = $this->auth->getUser();

        if ($code != '') {

            $orderModel = new Shoporder();
            $order = $orderModel->where('status', "<>", 'done')->where('open_code', $code)->find();
            if ($order['status'] != 'paying') {
                $user_id = $order['user_id'];
            }
        }
        $min = 10;
        $orgModel = new Org();

        if ($order_no != "") {
            $orderModel = new Shoporder();
            $order = $orderModel->where('order_no', $order_no)->find();
            $org = $orgModel->where('id', $order['org_id'])->find();
            if ($org) {
                $min = $org['open_time'];
            }


        } else {
            $org = $orgModel->where('id', $user['org_id'])->find();
            if ($org) {
                $min = $org['open_time'];
            }
        }


        $starTime = strtotime("+" . $min . " minute", time());


        $roomBookModel = new Shoproombook();

        if ($order_no != "") {
            $orderModel = new Shoporder();
            $order = $orderModel->where('order_no', $order_no)->find();
            $book = $roomBookModel->where('order_id', $order['id'])->where('start_time', "<=", $starTime)->where('end_time', ">", time())->find();
            if ($book['status'] == 'done') {
                $this->error("您的订单已经结束，不可开门");
            }
        } else {

            $book = $roomBookModel->where('status', 'in', ['undo', 'doing'])->
            where('user_id', $user_id)->where('end_time', ">", time())->order('start_time', 'desc')->find();


            if (!$book) {
                $msg = "您没有预定的订单";
                $this->success($msg);
            }
            if ($book['start_time'] > $starTime) {

                $msg = "您预约时间未到，无法开门";

                $this->success($msg);
            }
        }

        if ($user['id'] == 6153) {
            //error_log("===cmd book=open2=".json_encode($book));

        } else {
            //error_log("===cmd book=open=".json_encode($book));

        }


        $msg = "发送开门指令";


        $deviceModel = new Shopdevice();
        $sec = 0;
        if ($type == 'door') {//大门
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', -1)->find();
            $sec = 60;
            if ($device) {
                //发送指令

                $sn = $device['sn'];
                $req = array();
                $req['sec'] = $sec;
                $req['orderNo'] = getOrderSn();
                $req['sn'] = $sn;
                $req['voice'] = "欢迎光临";
                if ($device['prod'] == 1) {

                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {

                    $deviceService = new DeviceService();
                    $doorReq = array();
                    $doorReq['open'] = 1;
                    $doorReq['open2'] = 1;
                    $doorReq['open3'] = 1;
                    $doorReq['open4'] = 1;
                    $doorReq['device_sn'] = $device['device_sn'];


                    $deviceService->dxIotDoor($doorReq);
                }
                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => -1]);


            }
        } else {//包厢

            //error_log($order_no."=======".json_encode($book));
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
            $orderModel = new Shoporder();
            $order = $orderModel->where('id', $book['order_id'])->find();
            $orderNo = $order['order_no'];
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
            $sn = $device['sn'];

            $sec = $minute * 60;

            if ($device) {


                $req = array();
                $req['sec'] = $sec;
                $req['orderNo'] = $orderNo;
                $req['sn'] = $sn;
                $req['voice'] = "";

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $book['room_id'])->update(['status' => 'busy']);

                $roomBookModel->where('id', $book['id'])->update(['status' => 'doing']);
                $orderModel->where('id', $book['order_id'])->update(['status' => 'doing']);

                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                if ($device['prod'] == 1) {
                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {

                    $deviceService = new DeviceService();
                    $doorReq = array();
                    $doorReq['open'] = 1;
                    $doorReq['open2'] = 1;
                    $doorReq['open3'] = 1;
                    $doorReq['open4'] = 1;
                    $doorReq['device_sn'] = $device['device_sn'];

                    $timeReq = array();
                    $timeReq['device_sn'] = $device['device_sn'];
                    $timeReq['sec'] = $minute * 60;
                    $timeReq['time'] = time();
                    $deviceService->dxIotDoor($doorReq);
                    $deviceService->dxIotTime($timeReq);

                }

                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'order_no' => $orderNo, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => $book['room_id']]);

            }

        }


        $ret = array();
        $ret['is_bt'] = $device['is_bt'];
        $ret['room_id'] = $device['room_id'];
        $ret['shop_id'] = $device['shop_id'];

        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();

        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$device['shop_id'])->find();

                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['book_start'] = time();
                $lockReq['book_end'] = time() + $sec;
                $lockReq['lockId'] = $lock['lockId'];

                $lockService->openKtvLock($lockReq, $shop);//设置为订单期间常开
//                $lockReq = array();
//                $lockReq['lockId'] = $lock['lockId'];
//                $lockService->openLock($lockReq);

            }
        }

        $this->success($msg, $ret);


    }


    public function dxOpen2()
    {

        $msg = "";
        $type = $this->request->param('type');
        $code = $this->request->param('code');
        $order_no = $this->request->param('order_no');
        $user_id = $this->auth->getUser()['id'];
        $user = $this->auth->getUser();
        $orderModel = new Shoporder();

        if ($code != '') {

            $order = $orderModel->where('status', "<>", 'done')->where('open_code', $code)->find();
            if ($order['status'] != 'paying') {
                $user_id = $order['user_id'];
            }
        }
        $min = 10;
        $orgModel = new Org();

        if ($order_no != "") {
            $orderModel = new Shoporder();
            $order = $orderModel->where('order_no', $order_no)->find();
            $org = $orgModel->where('id', $order['org_id'])->find();
            if ($org) {
                $min = $org['open_time'];
            }


        } else {
            $org = $orgModel->where('id', $user['org_id'])->find();
            if ($org) {
                $min = $org['open_time'];
            }
        }


        $starTime = strtotime("+" . $min . " minute", time());


        $roomBookModel = new Shoproombook();

        if ($order_no != "") {
            $order = $orderModel->where('order_no', $order_no)->find();
            $book = $roomBookModel->where('order_id', $order['id'])->where('start_time', "<=", $starTime)->where('end_time', ">", time())->find();
            if ($book['status'] == 'done') {
                $this->error("您的订单已经结束，不可开门");
            }
        } else {

            $book = $roomBookModel->where('status', 'in', ['undo', 'doing'])->
            where('user_id', $user_id)->where('end_time', ">", time())->order('start_time', 'desc')->find();


            if (!$book) {
                $msg = "您没有预定的订单";
                $this->success($msg);
            }

        }

        $startTime = time();
        if ($startTime < $book['start_time']) {
            $endTime = $book['end_time'];
            $checkStart = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', "<=", $startTime)->where("end_time", ">=", $startTime)->find();
            $checkEnd = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', "<=", $endTime)->where("end_time", ">=", $endTime)->find();
            $checkEnd3 = $roomBookModel->where('order_id', "<>", $book['order_id'])->where('status', 'in', ['undo', 'doing'])->where('room_id', $book['room_id'])->where('start_time', ">=", $startTime)->where("end_time", "<=", $endTime)->find();

            if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
                $this->error("此时间不能提前开门");
            } else {
                $newMin = floor(($book['end_time'] - $book['start_time']) % 86400 / 60);

                $end = strtotime("+" . $newMin . " minute", time());
                //error_log("======test==".$end);
                $orderModel->where('id', $book['order_id'])->update(['book_start' => time(), 'book_end' => $end]);
                $roomBookModel->where('id', $book['id'])->update(['start_time' => time(), 'end_time' => $end]);
                $book = $roomBookModel->where('id', $book['id'])->find();

            }


        } else {

            if ($starTime < $book['start_time']) {
                $this->error("您预约的时间未到");
            }
        }


        if ($user['id'] == 6153) {
            //error_log("===cmd book=open2=".json_encode($book));

        } else {
            //error_log("===cmd book=open=".json_encode($book));

        }


        $msg = "发送开门指令";


        $deviceModel = new Shopdevice();
        $sec = 0;
        if ($type == 'door') {//大门
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', -1)->find();
            $sec = 60;
            if ($device) {
                //发送指令

                $sn = $device['sn'];
                $req = array();
                $req['sec'] = $sec;
                $req['orderNo'] = getOrderSn();
                $req['sn'] = $sn;
                $req['voice'] = "欢迎光临";
                if ($device['prod'] == 1) {

                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {

                    $deviceService = new DeviceService();
                    $doorReq = array();
                    $doorReq['open'] = 1;
                    $doorReq['open2'] = 1;
                    $doorReq['open3'] = 1;
                    $doorReq['open4'] = 1;
                    $doorReq['device_sn'] = $device['device_sn'];


                    $deviceService->dxIotDoor($doorReq);
                }
                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => -1]);


            }
        } else {//包厢

            //error_log($order_no."=======".json_encode($book));
            $device = $deviceModel->where('shop_id', $book['shop_id'])->where('room_id', $book['room_id'])->find();
            $orderModel = new Shoporder();
            $order = $orderModel->where('id', $book['order_id'])->find();
            $orderNo = $order['order_no'];
            $minute = floor(($book['end_time'] - time()) % 86400 / 60);
            $sn = $device['sn'];
            $sec = $minute * 60;

            if ($device) {


                $req = array();
                $req['sec'] = $minute * 60;
                $req['orderNo'] = $orderNo;
                $req['sn'] = $sn;
                $req['voice'] = "";

                $shopRoomModel = new Shoproom();
                $shopRoomModel->where('id', $book['room_id'])->update(['status' => 'busy']);

                $roomBookModel->where('id', $book['id'])->update(['status' => 'doing']);
                $orderModel->where('id', $book['order_id'])->update(['status' => 'doing']);

                $roomCleanModel = new Shoproom();
                $roomCleanModel->where('id', $order['room_id'])->update(['is_clean' => 1]);


                if ($device['prod'] == 1) {
                    $ret = http_post_json($this->openCmdUrl, json_encode($req));
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 0) {
                        $msg = "正在打开中";
                    }
                } else {

                    $deviceService = new DeviceService();
                    $doorReq = array();
                    $doorReq['open'] = 1;
                    $doorReq['open2'] = 1;
                    $doorReq['open3'] = 1;
                    $doorReq['open4'] = 1;
                    $doorReq['device_sn'] = $device['device_sn'];

                    $timeReq = array();
                    $timeReq['device_sn'] = $device['device_sn'];
                    $timeReq['sec'] = $minute * 60;
                    $timeReq['time'] = time();
                    $deviceService->dxIotDoor($doorReq);
                    $deviceService->dxIotTime($timeReq);

                }

                $cmdModel = new Cmdlog();
                $cmdModel->insert(['user_id' => $user_id, 'order_no' => $orderNo, 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $book['shop_id'], 'room_id' => $book['room_id']]);

            }

        }


        $ret = array();
        $ret['is_bt'] = $device['is_bt'];
        $ret['room_id'] = $device['room_id'];
        $ret['shop_id'] = $device['shop_id'];

        $deviceLockModel = new Devicelock();
        $lock = $deviceLockModel->where('room_id', $device['room_id'])->find();

        if ($lock) {
            if ($lock['is_gateway'] == 1) {
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$device['shop_id'])->find();

                //网关开锁
                $lockService = new LockService();
                $lockReq = array();
                $lockReq['book_start'] = time();
                $lockReq['book_end'] = time() + $sec;
                $lockReq['lockId'] = $lock['lockId'];

                $lockService->openKtvLock($lockReq, $shop);//设置为订单期间常开
//                $lockService = new LockService();
//                $lockReq = array();
//                $lockReq['lockId'] = $lock['lockId'];
//                $lockService->openLock($lockReq);

            }
        }

        $this->success($msg, $ret);


    }

    //判断时间段是否重叠
    protected function isOverlap($start1, $end1, $start2, $end2): bool
    {
        if ($end1 < $start2 || $start1 > $end2) {
            return false;
        }
        return true;
    }

    protected function checkUseTime($bookSt, $bookEt, $useTime)
    {

        try {
            list($useSt, $useEt) = explode('~', $useTime);
        } catch (Exception $e) {
            $this->error('请填写正确的时间范围');
        }

        $date = date('Y-m-d', $bookSt);
        $z = strtotime($date . " 23:59:59");//判断每天最大时间节点

        $use_st = strtotime($date . " " . $useSt);
        $use_et = strtotime($date . " " . $useEt);
        if ($use_st > $use_et) {
            if ($bookEt <= $z) {
                if ($use_st <= $bookSt) {
                    $use_et += 86400;
                } else {
                    $use_st -= 86400;
                }
            } else {
                $use_et += 86400;
            }

        }
        if ($bookSt >= $use_st && $bookEt <= $use_et) {
            return true;
        }
        return false;
    }
}
